package com.iplant.basic.controller.bfc;

import com.iplant.base.controller.BaseController;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.excel.ServerExcelUtils;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.FtpUtil;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.general.ThumbnailsUtils;
import com.iplant.basic.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/api/Upload")
public class UploadController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(UploadController.class);

	public UploadController() {
		// TODO Auto-generated constructor stub
	}

	@PostMapping("/Submit")
	Object Submit(HttpServletRequest request, MultipartFile[] files) {
		Map<String, Object> wResult = new HashMap<String, Object>();
		String wMsg = "";

		try {

			if (files.length == 0) {
				MultipartHttpServletRequest wMR = (MultipartHttpServletRequest) request;
				files = wMR.getFileMap().values().toArray(new MultipartFile[0]);
			}

			if (files.length == 0) {
				wMsg = "提示：没有要上传的文件！";
				return GetResult(RetCode.SERVER_CODE_ERR, wMsg, null, null);
			}

			List<String> wList = new ArrayList<String>();
			String wPath = "";
			for (int i = 0; i < files.length; i++) {
				MultipartFile wCurFile = files[i];
				if (wCurFile == null || wCurFile.getSize() < 1) {
					continue;
				}
				// 获取保存路径
				if (i >= 5) {
					break;
				}
				wPath = "";
				String wFilesUrl = "";
				Calendar wDateTime = Calendar.getInstance();
				if (Constants.Client_Upload_Save_Path.indexOf('/') == 0) {
					wFilesUrl = Constants.Client_Upload_Save_Path.substring(1)
							+ StringUtils.parseCalendarToString(wDateTime, "yyyy/MM/dd/");
				} else {
					wFilesUrl = Constants.Client_Upload_Save_Path
							+ StringUtils.parseCalendarToString(wDateTime, "yyyy/MM/dd/");
				}

				File file = new File(Constants.getStaticPath() + wFilesUrl);
				if (!file.exists())// 路径不存在则创建
				{
					file.mkdirs();
				}

				// 获取文件名
				String wFileName = wCurFile.getOriginalFilename();
				if (wFileName == null) {
					continue;
				}
				// 文件后缀名
				String wFilePostfixName = wFileName.substring(wFileName.lastIndexOf(".") + 1);
				String wNewFileName = wFileName.substring(0, wFileName.lastIndexOf("."));
				// 新文件名
				if (wFilePostfixName != null) {
					wFilePostfixName = wFilePostfixName.toLowerCase();
				}

				wNewFileName = StringUtils.Format("{0}_{1}_{2}.{3}", wNewFileName,
						StringUtils.parseCalendarToString(wDateTime, "HHmmss"), UUID.randomUUID(), wFilePostfixName);

				wPath = wFilesUrl + wNewFileName;

				File wFile = new File(Constants.getStaticPath() + wPath);
				wCurFile.transferTo(wFile);

				if (Constants.ImageSuffixList.contains(wFilePostfixName)) {
					// 压缩图片文件

					ThumbnailsUtils.Compress(Constants.getStaticPath() + wPath, Constants.getStaticPath() + wPath);

				}

				FtpUtil.getInstance(Constants.FTPServerURL, Constants.FTPServerPORT, Constants.FTPUserName,
						Constants.FTPPassword, Constants.FTPServerDir).upload(wFile, wFilesUrl, wNewFileName);

				if (wFilePostfixName.equalsIgnoreCase("mp4")) {
					Constants.VideoChangeSource.add(wPath);
				}

				wList.add(GetProjectName(request) + "/" + wPath);
			}

			if (StringUtils.isEmpty(wPath)) {
				GetResult(RetCode.SERVER_CODE_ERR, "上传的文件不能为空!");
			} else {

				Map<String, Object> wResultObject = new HashMap<String, Object>();
				wResultObject.put("list", wList);
				wResultObject.put("file_id", GetProjectName(request) + "/" + wPath);
				wResultObject.put("file_url", GetProjectName(request) + "/" + wPath);
				wResult = GetResult(RetCode.SERVER_CODE_SUC, wResultObject);
			}

		} catch (Exception ex) {
			logger.error("Submit", ex);

			wResult = GetResult(RetCode.SERVER_CODE_ERR, wMsg + "\n" + ex.toString());
		}
		return wResult;
	}

	@PostMapping("/SubmitNormal")
	Object SubmitNormal(HttpServletRequest request, MultipartFile[] files) {
		Map<String, Object> wResult = new HashMap<String, Object>();
		String wMsg = "";

		try {

			if (files.length == 0) {
				MultipartHttpServletRequest wMR = (MultipartHttpServletRequest) request;
				files = wMR.getFileMap().values().toArray(new MultipartFile[0]);
			}

			if (files.length == 0) {
				wMsg = "提示：没有要上传的文件！";
				return GetResult(RetCode.SERVER_CODE_ERR, wMsg, null, null);
			}
			List<String> wList = new ArrayList<String>();
			String wPath = "";
			for (int i = 0; i < files.length; i++) {
				MultipartFile wCurFile = files[i];
				if (wCurFile == null || wCurFile.getSize() < 1) {
					continue;
				}
				// 获取保存路径
				if (i >= 5) {
					break;
				}
				wPath = "";
				String wFilesUrl = "";
				Calendar wDateTime = Calendar.getInstance();
				if (Constants.Client_Upload_Save_Path.indexOf('/') == 0) {
					wFilesUrl = Constants.Client_Upload_Save_Path.substring(1)
							+ StringUtils.parseCalendarToString(wDateTime, "yyyy/MM/dd/");
				}

				else {
					wFilesUrl = Constants.Client_Upload_Save_Path
							+ StringUtils.parseCalendarToString(wDateTime, "yyyy/MM/dd/");
				}

				File file = new File(Constants.getStaticPath() + wFilesUrl);
				if (!file.exists())// 路径不存在则创建
				{
					file.mkdirs();
				}

				// 获取文件名
				String wFileName = wCurFile.getOriginalFilename();
				if (wFileName == null) {
					continue;
				}
				// 文件后缀名
				String wFilePostfixName = wFileName.substring(wFileName.lastIndexOf(".") + 1);
				String wNewFileName = wFileName.substring(0, wFileName.lastIndexOf("."));
				// 新文件名
				if (wFilePostfixName != null) {
					wFilePostfixName = wFilePostfixName.toLowerCase();
				}

				wNewFileName = StringUtils.Format("{0}_{1}_{2}.{3}", wNewFileName,
						StringUtils.parseCalendarToString(wDateTime, "HHmmss"), UUID.randomUUID(), wFilePostfixName);

				wPath = wFilesUrl + wNewFileName;

				File wFile = new File(Constants.getStaticPath() + wPath);
				wCurFile.transferTo(wFile);

				FtpUtil.getInstance(Constants.FTPServerURL, Constants.FTPServerPORT, Constants.FTPUserName,
						Constants.FTPPassword, Constants.FTPServerDir).upload(wFile, wFilesUrl, wNewFileName);

				if (wFilePostfixName.equalsIgnoreCase("mp4")) {
					Constants.VideoChangeSource.add(wPath);
				}

				wList.add(wPath);
			}

			if (StringUtils.isEmpty(wPath)) {
				GetResult(RetCode.SERVER_CODE_ERR, "上传的文件不能为空!");
			} else {

				Map<String, Object> wResultObject = new HashMap<String, Object>();
				wResultObject.put("list", wList);
				wResultObject.put("file_id", GetProjectName(request) + "/" + wPath);
				wResultObject.put("file_url", GetProjectName(request) + "/" + wPath);
				wResult = GetResult(RetCode.SERVER_CODE_SUC, wResultObject);
			}

		} catch (Exception ex) {
			logger.error(ex.toString());

			GetResult(RetCode.SERVER_CODE_ERR, wMsg + "\n" + ex.toString());
		}
		return wResult;
	}

	@GetMapping("/DownLoadFile")
	ResponseEntity<FileSystemResource> DownLoadFile(HttpServletRequest request) {

		try {

			String wFilePath = StringUtils.parseString(request.getParameter("Path"));

			int wIsAbsolute = StringUtils.parseInt(request.getParameter("IsAbsolute"));
			String wFilesUrl = "";
			if (wIsAbsolute == 1) {
				wFilesUrl = wFilePath;

			} else {
				String wProjectName = GetProjectName(request);
				if (wFilePath.startsWith(wProjectName)) {
					wFilePath = wFilePath.substring(wProjectName.length());
				}

				if (Constants.Client_Upload_Save_Path.indexOf('/') == 0) {
					wFilesUrl = Constants.Client_Upload_Save_Path.substring(1);
				}

				else {
					wFilesUrl = Constants.Client_Upload_Save_Path;
				}
				if (wFilePath.indexOf("/") != 0) {
					wFilePath = "/" + wFilePath;
				}

				wFilesUrl += wFilePath;
			}

			File file = new File(wFilesUrl);

			if (file.exists()) {
				return export(file);
			}

		} catch (Exception ex) {
			logger.error(ex.toString());

			return null;
		}
		return null;
	}

	public ResponseEntity<FileSystemResource> export(File file) {
		if (file == null) {
			return null;
		}
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		headers.add("Content-Disposition", "attachment; filename=" + file.getName());
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");
		headers.add("Last-Modified", new Date().toString());
		headers.add("ETag", String.valueOf(System.currentTimeMillis()));

		FileSystemResource wFileSystemResource = new FileSystemResource(file);

		return ResponseEntity.ok().headers(headers).contentLength(file.length())
				.contentType(MediaType.parseMediaType("application/octet-stream")).body(wFileSystemResource);
	}

	@PostMapping("/ImportExcel")
	Object ImportExcel(HttpServletRequest request, @RequestParam("files")MultipartFile[] files) {
		Map<String, Object> wResult = new HashMap<String, Object>();
		String wMsg = "";
		try {

			if (files.length == 0) {
				MultipartHttpServletRequest wMR = (MultipartHttpServletRequest) request;
				files = wMR.getFileMap().values().toArray(new MultipartFile[0]);
			}

			if (files.length == 0) {
				wMsg = "提示：没有要上传的Excel文件！";
				return GetResult(RetCode.SERVER_CODE_ERR, wMsg, null, null);
			}

			for (int i = 0; i < files.length; i++) {
				MultipartFile wCurFile = files[i];

				if (wCurFile == null || wCurFile.getSize() < 1) {
					continue;
				}

				// 获取文件名
				String wFileName = wCurFile.getOriginalFilename();
				if (wFileName == null) {
					continue;
				}

				ServiceResult<List<Map<String, Object>>> wReturnResult = ServerExcelUtils.getInstance().Import(wCurFile,
						"");

				wResult = GetResult(RetCode.SERVER_CODE_SUC, wReturnResult.getFaultCode(), wReturnResult.getResult(),
						null);
				break;
			}
		} catch (Exception ex) {
			logger.error(ex.toString());
			wResult = GetResult(RetCode.SERVER_CODE_ERR, wMsg + "\n" + ex.toString());
		}

		return wResult;
	}

	@PostMapping("/ExportExcel")
	Object ExportExcel(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
		Map<String, Object> wResult = new HashMap<String, Object>();
		try {

			if (!wParam.containsKey("data") || !wParam.containsKey("head") || !wParam.containsKey("fileName")) {
				wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
				return wResult;
			}
			List<Map<String, Object>> wList = CloneTool.CloneArray(wParam.get("data"));

			@SuppressWarnings("unchecked")
			Map<String, String> wHeadList = CloneTool.Clone(wParam.get("head"), Map.class);

			String wTitle = wParam.containsKey("title") ? StringUtils.parseString(wParam.get("title")) : "";

			String wFileName = StringUtils.parseString(wParam.get("fileName"));

			List<String> wOrderList = wParam.containsKey("order")
					? CloneTool.CloneArray(wParam.get("order"), String.class)
					: new ArrayList<>();

			ServiceResult<String> wPath = ServerExcelUtils.getInstance().Export(wList, wHeadList, wTitle, wFileName,
					wOrderList, Constants.Client_Upload_Excel_Save_Path, Constants.getStaticPath());
			Map<String, Object> wInfo = new HashMap<String, Object>();
			wInfo.put("path", GetProjectName(request) + wPath.getResult());

			if (StringUtils.isEmpty(wPath.getFaultCode())) {
				wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wInfo);
			} else {
				wResult = GetResult(RetCode.SERVER_CODE_ERR, wPath.getFaultCode(), null, wInfo);
			}

		} catch (Exception ex) {
			logger.error(ex.toString());
			wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
		}
		return wResult;
	}

}
